package com.exercise.AndroidCamera;
/*
기능 : 메인 화면인 지도와 슬라이드 리스트 버튼들이 담겨있다. 메인 화면이다
작성 : 하드캔
완료일 : 2014.09.26 
	*/
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.ActionBar;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.AlertDialog;
import android.app.ActionBar.Tab;
import android.app.ActionBar.TabListener;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.provider.ContactsContract.CommonDataKinds.Event;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.AsyncTaskLoader;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.view.textservice.SentenceSuggestionsInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.exercise.AndroidCamera.SlideListAdapter;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.Projection;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

public class MainActivity extends FragmentActivity implements View.OnClickListener,OnMarkerClickListener, TabListener, ActionBar.OnNavigationListener, LocationListener {

	private DrawerLayout mDrawerLayout;
	private ListView mDrawerList;
	private SlideListAdapter slideAdapter;
	private GoogleMap mmap;
	private LocationManager locationManager;
	private Location mylocation;
	private String provider;
	private String hotTitle;
	private double lat,lng;
	private Geocoder geoCoder = new Geocoder(this, Locale.KOREAN);
	private ArrayList<Marker> m=new ArrayList<Marker>();
	private ArrayList<Integer> locationId = new ArrayList<Integer>();
	private ArrayList<Double> lattitude = new ArrayList<Double>();
	private ArrayList<Double> longitude = new ArrayList<Double>();
	private ArrayList<String> pointTitle = new ArrayList<String>();
	private ArrayList<Integer> groupId = new ArrayList<Integer>();
	private double meter;
	private int drawerOpen=0;
	Intent mIntent;
	private TimerTask mTask;
	private Timer mTimer;
	MarkerOptions marker = new MarkerOptions();
	StringBuffer mAddress = new StringBuffer();
	LatLng startingPoint /*= new LatLng(37.56654,126.97797)*/; 
	CameraPosition cp/*=new CameraPosition.Builder().target(startingPoint).zoom(16).build()*/;
	
	public static final int new_post = Menu.FIRST+1;
	public static final int find_friends = Menu.FIRST+2;
	public static final int inactive_location = Menu.FIRST+3;
	public static String userID;
	public static String locationID;	
	
	public static LatLng DEFAULT_GP = new LatLng(37.566500, 126.978000);
	private double minLatitude =  +81;
	private double maxLatitude =  -81;
	private double minLongitude = +181;
	private double maxLongitude = -181;
	private double mapnotrhlat;
	private double mapsouthlat;
	private double mapnorthlng;
	private double mapsouthlng;
	private double hotlatitude;
	private double hotlongitude;
	private ProgressDialog progressDialog;
	private String errorString = "";
	private ImageButton searchBt;
	private GoogleMapkiUtil httpUtil;
	private AlertDialog errorDialog;
	private ActionBarDrawerToggle mDrawerToggle;
	Uri photo_uri;
	
	public final static int CAMERA_SHOOT = 100;
	public final static int GET_PICTURE = 200;
	
	private Bitmap bitmap;
	private ImageView preview;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_layout);

		userID = getIntent().getExtras().getString("userID");
		locationID = getIntent().getExtras().getString("locationID");
		
		if(getIntent().getExtras().getDouble("select_radius")!=0.0)
			 meter = getIntent().getExtras().getDouble("select_radius");
		else
			meter = 1.0;
		
		Log.d("llog",""+getIntent().getExtras().getDouble("select_radius"));
		FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
		transaction.commit();
		
		mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
		mDrawerList = (ListView)findViewById(R.id.left_drawer);
		
		slideAdapter = new SlideListAdapter(this, R.layout.side_list_layout, userID, meter, MainActivity.this);
		mDrawerList.setAdapter(slideAdapter);
		
		ActionBar ab = getActionBar();
		ab.setDisplayHomeAsUpEnabled(true);
		ab.setDisplayShowCustomEnabled(true);
		
		GooglePlayServicesUtil.isGooglePlayServicesAvailable(MainActivity.this);
		locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
		Log.d("current location", startingPoint + "");
		
		Criteria criteria = new Criteria();
		provider = locationManager.getBestProvider(criteria, true);
		/*위치서버스제공동의를 물어보는 다이얼로그*/
		if(!locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
			new AlertDialog.Builder(MainActivity.this)
	        .setTitle("위치수신동의를 하셔야 합니다")
	        .setNeutralButton("확인" ,new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS), 0);
				}
			}).setOnCancelListener(new DialogInterface.OnCancelListener() {
				@Override
				public void onCancel(DialogInterface dialog) {
					finish();
				}
			})
	        .show();
		}else{   
			locationManager.requestLocationUpdates(provider, 1, 1, (LocationListener) MainActivity.this);
			setUpMapIfNeeded();
		}
		
	      findViewById(R.id.search).setOnClickListener(onNameSearch);
	      httpUtil = new GoogleMapkiUtil();
	      
	      errorDialog = new AlertDialog.Builder(this).setTitle("?�넫占쏙옙占�?占쏙옙占쏙옙占쏙옙?")
	            .setMessage(errorString).setPositiveButton("?�넫占썹뙴占�?占쎌슜占쏙옙?占쏙옙占쏙옙", null)
	            .create();

		
		mmap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();


		findViewById(R.id.camerabutton).setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				// sd 카드의 mount 여부 검사.
	    		if( Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) ){
		    		// sd 카드 경로 가져오기
		    		String SD_path = Environment.getExternalStorageDirectory().getAbsolutePath(); //sd 카드 루트경로.
		    		SD_path += "/PostMemories"; // 사용할 폴더. 경로만 지정한것이지 실제로 폴더가 생기거나 한건 아니다.
		    		
		    		// sd 카드에 사용할 폴더있는지 검사후 없으면 생성.
		    		File photoFile = new File(SD_path);
		    		if(!photoFile.exists()){
		    			photoFile.mkdir();
		    		}  
		    		SimpleDateFormat timeStampFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
		    		String filename = "/eastgem test shoot " + timeStampFormat.format(new Date()).toString() + ".jpg";

		    		// 폴더 생성이나 점검을 완료했으니 파일을 직접 생성하자.
		    		photoFile = new File(SD_path + filename); // 사진이 저장될 경로 및 파일명.
		    		photo_uri = Uri.fromFile(photoFile);

	    			// 카메라 Activity 부를때 사용할 인텐트
		    		Intent intent_Camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		    		intent_Camera.putExtra(MediaStore.EXTRA_OUTPUT, photo_uri);
		    		startActivityForResult(intent_Camera, CAMERA_SHOOT);
	    		}else{
	    		}
			}	
		});
		
		/*게시물 작성 레이아웃으로 넘어감*/
		findViewById(R.id.write).setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				locaAsyncTask locaAsync = new locaAsyncTask();
		    	locaAsync.execute();
			}
		});
		
		/*반경설정*/
		findViewById(R.id.scale).setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mIntent = new Intent(MainActivity.this, SettingRadiusActivity.class);
		        mIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		    	mIntent.putExtra("userID", userID);
		    	mIntent.putExtra("meter", meter);
	    		startActivity(mIntent);
				
			}
		});
		caldistance();

		getActionBar().setTitle("Post Memories");
		getActionBar().setDisplayShowHomeEnabled(false);
	}
	
	 @Override
		protected void onActivityResult(int requestCode, int resultCode, Intent data) {
			super.onActivityResult(requestCode, resultCode, data);
			switch (requestCode) {
			case 0:
				 locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
			        Criteria criteria = new Criteria();
			        provider = locationManager.getBestProvider(criteria, true);
			        if(provider==null){
						finish();
				}else{
					locationManager.requestLocationUpdates(provider, 1L, 2F, MainActivity.this);
			        	setUpMapIfNeeded();
				}			      
				break;
			case CAMERA_SHOOT:
				if(resultCode == Activity.RESULT_OK){ // 정상적으로 이미지를 선택했을경우.
					try{ // 이미지 선택의 경우 data 가 null 이 들어오는 일은 없지 싶다...
						Uri select_uri = data.getData();
						
						Cursor c = getContentResolver().query(Uri.parse(select_uri.toString()), null,null,null,null);
						c.moveToNext();
						
						// 비트맵 이미지를 업로드 또는 가공할경우 아래의 변수를 사용하도록 한다.
						String physical_path = c.getString(c.getColumnIndex(MediaStore.MediaColumns.DATA)).toString().substring(5).replaceAll("%3B", ";").replaceAll("%20"," ");
						if(bitmap != null && !bitmap.isRecycled()){ bitmap.recycle(); bitmap = null; }
						bitmap = BitmapFactory.decodeFile(physical_path);


						preview.setImageBitmap(bitmap);
					}catch (Exception e) {
					}
				}
				break;
			default:
				break;

			}
		}
	 @Override
		public void onBackPressed() {
			this.finish();
		}

	    @Override
	    protected void onResume() {
	        super.onResume();
	        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 1, this);
	        setUpMapIfNeeded();
	    }

	    @Override
	    protected void onPause() {
	        super.onPause();
	        locationManager.removeUpdates(this);
	    }
	    
	    private void setUpMapIfNeeded() {
			// TODO Auto-generated method stub
	    	if (mmap == null) {
	    		
				mylocation=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
				mmap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
				
						if (mmap != null) {
							setUpMap();
						}
				}
		}
	private void setUpMap() {
	 	mmap.setMyLocationEnabled(true);
	 	mmap.getMyLocation();	      
		}
		boolean locationTag=true;
		
	
	@Override
	/*슬라이드리스트를 보여주기 위한 함수*/
	public boolean onOptionsItemSelected(MenuItem item) {
	    String text = null;
	     
	    switch(item.getItemId()){
	    
	    case android.R.id.home:
	    	if(drawerOpen==0){
	    		mDrawerLayout.openDrawer(mDrawerList);
	    		drawerOpen=1;
	    	}
	    	else{
	    		mDrawerLayout.closeDrawers();
	    		drawerOpen=0;
	    	}
	    	break;

	    default:
	        return false;
	    }
	    return true;
	}
	
	@Override
	public boolean onNavigationItemSelected(int itemPosition, long itemId) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onTabSelected(Tab tab, android.app.FragmentTransaction ft) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onTabUnselected(Tab tab, android.app.FragmentTransaction ft) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onTabReselected(Tab tab, android.app.FragmentTransaction ft) {
		// TODO Auto-generated method stub
		
	}

	@Override
	/*위치가 변화할때만 GPS센서값을 이용 거리를 계산하고 마커를 지도에 찍는다*/
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub
		if(locationTag){
		mmap.clear();
		m.clear();
		locationId.clear();
		lattitude.clear();
		longitude.clear();
		if(locationTag){
		        lat = location.getLatitude();
		        lng = location.getLongitude();
		        startingPoint = new LatLng(lat, lng);
		        cp =new CameraPosition.Builder().target(startingPoint).zoom(16).build();
		        mmap.moveCamera(CameraUpdateFactory.newLatLngZoom(startingPoint, 5));			
				mmap.animateCamera(CameraUpdateFactory.newCameraPosition(cp));
		        try{
		        List<Address> addresses;
		        addresses = geoCoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
		        for(Address addr: addresses){
		         int index = addr.getMaxAddressLineIndex();
		         for(int i=0;i<=index;i++){
		          mAddress.append(addr.getAddressLine(i));
		          mAddress.append(" ");
		         }
		         mAddress.append("\n");
		        }
		       } catch (IOException e) {
		        e.printStackTrace();
		       }
		       
		       locationTag=false;
		}
		caldistance();
		sendLocationAsync sendLocaId = new sendLocationAsync();
		sendLocaId.execute();
		}
	}
	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean onMarkerClick(Marker arg0) {
		// TODO Auto-generated method stub
		return false;
	}
	
	 @Override
	 public boolean onKeyDown(int keyCode, KeyEvent event)
	 {
	  if( keyCode == KeyEvent.KEYCODE_BACK )
	  {

		  new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert).setTitle("로그아웃").setMessage("로그아웃 하시겠습니까?").setNegativeButton( "아니오", null )
	      .setPositiveButton("예", new DialogInterface.OnClickListener()

	   {
	     @Override
	     public void onClick( DialogInterface dialog, int which )
	     {
	       finish();
	     }
	   }).show(); 
	  
	   return true;
	  }
	  
	  return super.onKeyDown(keyCode, event);
	 }
	 
	 /*거리계산 함수*/
	 public void caldistance()
	 {
		 
		 mapnotrhlat = mmap.getProjection().getVisibleRegion().latLngBounds.northeast.latitude;
		 mapsouthlat = mmap.getProjection().getVisibleRegion().latLngBounds.southwest.latitude;
		 mapnorthlng = mmap.getProjection().getVisibleRegion().latLngBounds.northeast.longitude;
		 mapsouthlng = mmap.getProjection().getVisibleRegion().latLngBounds.southwest.longitude;
		 for(int i=0;i<locationId.size();i++)
		 {
			 if(calDistaneLocation(lat,lng,lattitude.indexOf(i),locationId.indexOf(i))<=meter){
				 marker.icon(BitmapDescriptorFactory.fromResource(R.drawable.markericon));
				 marker.position(startingPoint);
				 marker.title("Location");
				 marker.snippet("This is my location");
				 m.add(mmap.addMarker(marker));
				 mmap.setOnMarkerClickListener(this);
				 mmap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
						
						@Override
					public void onInfoWindowClick(Marker arg0) {
							// TODO Auto-generated method stub
							
					}
				});
			 }else{
				 double tm= calDistaneLocation(lat,lng,lattitude.indexOf(i),locationId.indexOf(i));
				 marker.icon(BitmapDescriptorFactory.fromResource(R.drawable.markericon));
				 marker.position(startingPoint);
				 marker.title("Location");
				 marker.snippet("This is my location");
				 m.add(mmap.addMarker(marker));
				 mmap.setOnMarkerClickListener(this);
			 }
		 }
		 readLocationAsync readLoca = new readLocationAsync();
		 readLoca.execute();
	 }
	 
	 /*현재 위치와 게시물의 거리를 계산*/
	 public Double calDistaneLocation(double lat1, double long1, double lat2, double long2) {
		 double EARTH_R, Rad, radLat1, radLat2, radDist; 
	     double distance, ret;

	        EARTH_R = 6371000.0;
	        Rad = Math.PI/180;
	        radLat1 = Rad * lat1;
	        radLat2 = Rad * lat2;
	        radDist = Rad * (long1 - long2);
	        
	        distance = Math.sin(radLat1) * Math.sin(radLat2);
	        distance = distance + Math.cos(radLat1) * Math.cos(radLat2) * Math.cos(radDist);
	        ret = EARTH_R * Math.acos(distance);
	        
	        double rslt = Math.round(Math.round(ret) / 1000);
	        String result = rslt + " km";
	        if(rslt == 0) result = Math.round(ret) +" m";

	        return rslt;

	 }
	 
	 /*서버와 연동하여 현재 위치를 서버에 보냄*/
	 protected String[] sendMapLocation(){
		 
		 	String pString = null;
			HttpURLConnection conn = null;
			BufferedReader br = null;
			JSONObject obj = new JSONObject();
			JSONArray arr = new JSONArray();
			
			String[] result = new String[2];
			result[0] = "error"; //JSON flag
			result[1] = null; //message
			
			try{
	       	StringBuilder builder = new StringBuilder();
	       	
	       	URL url = new URL("http://54.199.194.197/request_board_max.php");
	       	conn = (HttpURLConnection)url.openConnection();
	       	
	       	if(conn != null){
	       		conn.setConnectTimeout(15000);	
	       		conn.setReadTimeout(15000);
	       		conn.setDefaultUseCaches(false); 
	           	conn.setDoInput(true); 
	           	conn.setDoOutput(true);
	           	conn.setRequestMethod("POST");
	           	conn.setRequestProperty("content-type", "application/x-www-form-urlencoded"); 
	            StringBuffer buffer = new StringBuffer();
	            obj.put("location_id", arr.put(locationId.get(0)));
	               for(int i=1; i < locationId.size(); i++ ){
	                  System.out.println(locationId.get(i));
	                  if(locationId.get(i) != locationId.get(i-1))
	                	  obj.put("location_id", arr.put(locationId.get(i)));
	                  Log.d("location_id", obj+"");
	               }

	         	System.out.println(obj);
	         	
	         	buffer.append("location_id").append("=").append(obj);
	         	
	            OutputStreamWriter outStream = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
	            PrintWriter writer = new PrintWriter(outStream);
	            writer.write(buffer.toString());
	            writer.flush();
	            
	           InputStreamReader inputStream = new InputStreamReader(conn.getInputStream(), "UTF-8"); 
	           br = new BufferedReader(inputStream);
	              
	           	String line;
	           	while((line = br.readLine()) != null){
	           	   builder.append(line);
	           	}
	              
	           	br.close();
	           	pString =  builder.toString();
	           	JSONObject jObject = new JSONObject(pString);
	           	JSONArray latitude = new JSONArray(jObject.getString("latitude"));
	        	JSONArray longitude = new JSONArray(jObject.getString("longitude"));
	        	JSONArray title = new JSONArray(jObject.getString("title"));
	        	
	        	for(int i=0 ; i<lattitude.size(); i++){
	        		hotlatitude = Double.parseDouble(latitude.getString(i));
	        		hotlongitude = Double.parseDouble(longitude.getString(i));
	        		hotTitle = title.getString(i);
	        	}
	           	
	       	}else{
	       		
	       		throw new Exception("network error");
	       	}
	       	
	       }catch(SocketTimeoutException se){
	       	
	       	result[1] = "network error";
	       	
	       }catch(Exception e){
	       	
	       	result[1] = e.getMessage();
	       	
	       }finally{
	       	
	       	if(conn != null)
	       		conn.disconnect();

	       	if(br != null){
	       		try {
	       			br.close();
					} catch (Exception e2) {
						// TODO: handle exception
						result[1] = e2.getMessage();
					}
	       	}
	       }
	       return result;
		
	}
	 
	 /*서버가 위치를 받음*/
	 protected String[] readLocation(Context context ,double mapnotrhlat,double mapsouthlat,double mapnorthlng, double mapsouthlng)
	 {
		 	String pString = null;
			HttpURLConnection conn = null;
			BufferedReader br = null;
			
			String[] result = new String[2];
			result[0] = "error"; //JSON flag
			result[1] = null; //message
			
			try{
		       	StringBuilder builder = new StringBuilder();
		       	
		       	URL url = new URL("http://54.199.194.197/request_board.php");
		       	conn = (HttpURLConnection)url.openConnection();
		       	
		       	if(conn != null){
		       		conn.setConnectTimeout(150000);
		       		conn.setReadTimeout(150000);
		       		conn.setDefaultUseCaches(false);
		           	conn.setDoInput(true); 
		           	conn.setDoOutput(true);
		           	conn.setRequestMethod("POST"); 
		           	conn.setRequestProperty("content-type", "application/x-www-form-urlencoded"); 
		         	StringBuffer buffer = new StringBuffer();
		         	buffer.append("user_id").append("=").append(userID).append("&");
		         	if(slideAdapter.mode.equals("group"))
		         		buffer.append("view_mode").append("=").append("1").append("&");
		         	else if(slideAdapter.mode.equals("friend"))
		         		buffer.append("view_mode").append("=").append("2").append("&");
		         	else if(slideAdapter.mode.isEmpty() || slideAdapter.mode.equals("all")) 
		         		buffer.append("view_mode").append("=").append("0").append("&");
		         	buffer.append("east_lati").append("=").append(mapnotrhlat).append("&");
		         	buffer.append("north_long").append("=").append(mapnorthlng).append("&");
		         	buffer.append("west_lati").append("=").append(mapsouthlat).append("&");
		         	buffer.append("south_long").append("=").append(mapsouthlng);
	
		            OutputStreamWriter outStream = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
		            PrintWriter writer = new PrintWriter(outStream);
		            writer.write(buffer.toString());
		            writer.flush();
		            
		           InputStreamReader inputStream = new InputStreamReader(conn.getInputStream(), "UTF-8"); 
		           br = new BufferedReader(inputStream);
		              
		           	String line;
		           	while((line = br.readLine()) != null){
		           	   builder.append(line);
		           	}
		              
		           	br.close();
		           	
		           	pString =  builder.toString();
		           	
		           	JSONObject jObject = new JSONObject(pString);
		           	JSONArray titleObject = new JSONArray(jObject.getString("location_id"));
		           	JSONArray bIDObject = new JSONArray(jObject.getString("latitude"));
		           	JSONArray baseObject = new JSONArray(jObject.getString("longitude"));
		           	JSONArray title = new JSONArray(jObject.getString("title"));
		        	JSONArray viewGroup = new JSONArray(jObject.getString("group_id"));
		         
		           	for(int i=0;i<titleObject.length();i++) {
		          
		           			locationId.add(Integer.parseInt(titleObject.getString(i)));
		           			lattitude.add(Double.parseDouble(bIDObject.getString(i)));
		           			longitude.add(Double.parseDouble(baseObject.getString(i)));
		           			pointTitle.add(title.getString(i));
		           			groupId.add(Integer.parseInt(viewGroup.getString(i)));
		           		
		           	}
	           	
	       	}else{
	       		
	       		throw new Exception("network error");
	       	}
	       	
	       }catch(SocketTimeoutException se){
	       	
	       	result[1] = "network error";
	       	
	       }catch(Exception e){
	       	
	       	result[1] = e.getMessage();
	       	
	       }finally{
	       	
	       	if(conn != null)
	       		conn.disconnect();

	       	if(br != null){
	       		try {
	       			br.close();
					} catch (Exception e2) {
						// TODO: handle exception
						result[1] = e2.getMessage();
					}
	       	}
	       }
	       return result;
	 }
	 @Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		Projection g = mmap.getProjection();
		
		System.out.println(event.getX()+"touch touch"+
		event.getY());
		return super.onTouchEvent(event);
	}
	 public class sendLocationAsync extends AsyncTask<String, String, String>{
		 
		@Override
		protected String doInBackground(String... params) {
			sendMapLocation();
			return null;
		}
		@Override
		protected void onPostExecute(String result) {
			
			super.onPostExecute(result);
		}
		 
	 }
	 public class readLocationAsync extends AsyncTask<String, String, String> {
		 @Override
		protected void onPreExecute() {
			super.onPreExecute();
		}
		 @Override
		protected String doInBackground(String... params) {
			 readLocation(MainActivity.this, mapnotrhlat, mapsouthlat, mapnorthlng, mapsouthlng);
			return null;
		}
		 @Override
		 /*게시물을 보냄 마커에 게시물 일보가 노출됨*/
		protected void onPostExecute(String result) {
			 for(int i=0;i<locationId.size();i++)
			 {
				 if(calDistaneLocation(lat,lng,lattitude.get(i),longitude.get(i))<=meter){
					 if(groupId.get(i)==14)
						 marker.icon(BitmapDescriptorFactory.fromResource(R.drawable.friendview));
					 else if(groupId.get(i)== 1)
						 marker.icon(BitmapDescriptorFactory.fromResource(R.drawable.markericon));
					 else
						 marker.icon(BitmapDescriptorFactory.fromResource(R.drawable.groupview));
					 marker.position(new LatLng(lattitude.get(i),longitude.get(i)));
					 marker.title(pointTitle.get(i));
					 m.add(mmap.addMarker(marker));
					 mmap.setOnMarkerClickListener(MainActivity.this);
					 
				 }
				 

			 }
			 mmap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
					
					@Override
					/*마커 클릭시 게시물이 보이게 한다*/
				public void onInfoWindowClick(Marker arg0) {
						// TODO Auto-generated method stub
					for(int j=0; j < pointTitle.size(); j++){
						if(arg0.getTitle().equals(pointTitle.get(j))){
							Log.d("marker", marker.getTitle());
							Log.d("pointTitle", pointTitle.get(j));
							mIntent = new Intent(MainActivity.this, PostListActivity.class);
							mIntent.putExtra("userID", userID);
							if(slideAdapter.mode.equals("group")){
								mIntent.putExtra("groupID", "1");
							} else if(slideAdapter.mode.equals("friend")){
								mIntent.putExtra("groupID", "14");
							} else if(slideAdapter.mode.isEmpty() || slideAdapter.mode.equals("all")) {
								mIntent.putExtra("groupID", "0");
							}
							mIntent.putExtra("locationID", Integer.toString(locationId.get(j)));
							startActivity(mIntent);
							
						}
					}
				}
			});
			super.onPostExecute(result);
		}
		 @Override
		protected void onCancelled() {
			super.onCancelled();
		}
	 }
	
	 /*지도 검색을 위함 함수*/
	private View.OnClickListener onNameSearch = new View.OnClickListener() {

			@Override
			
			public void onClick(View arg0) {
				
				final LinearLayout linear = (LinearLayout) View.inflate(MainActivity.this, R.layout.dialog_map_namesearch, null);
				TextView addrTv = (TextView) linear.findViewById(R.id.dialog_map_search_addr);

				EditText nameEt = (EditText) findViewById(R.id.search_id);

				Location lo = mmap.getMyLocation();
				addrTv.setText(getAddres(lo.getLatitude(), lo.getLongitude()));
				
				if (nameEt.getText().length() > 0) {
					if (progressDialog != null && progressDialog.isShowing())
						return;
					progressDialog = ProgressDialog.show(
					MainActivity.this, "Wait", "잠시만 기다려 주세요.");
		
					httpUtil.requestMapSearch(new ResultHandler(MainActivity.this), nameEt.getText().toString(), addrTv.getText().toString());
		
					final InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
					imm.hideSoftInputFromWindow(nameEt.getWindowToken(), 0);
				}
				
			}
		};
		
		
		/*마커 클릭시 검색한 결과물이 보임*/
		private DialogInterface.OnClickListener onClickNameSearch = new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				AlertDialog ad = (AlertDialog) dialog;
				EditText nameEt = (EditText) ad.findViewById(R.id.dialog_map_search_et);
				TextView addrTv = (TextView) ad.findViewById(R.id.dialog_map_search_addr);
				
				if (nameEt.getText().length() > 0) {
					if (progressDialog != null && progressDialog.isShowing())
						return;
					progressDialog = ProgressDialog.show(
							MainActivity.this, "Wait", "잠시만 기다려 주세요.");
		
					httpUtil.requestMapSearch(new ResultHandler(MainActivity.this), nameEt.getText().toString(), addrTv.getText().toString());
		
					final InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
					imm.hideSoftInputFromWindow(nameEt.getWindowToken(), 0);
				}
			}
		};
		
		static class ResultHandler extends Handler {
			private final WeakReference<MainActivity> mActivity;
			
			ResultHandler(MainActivity activity) {
				mActivity = new WeakReference<MainActivity>(activity);
			}
			
			@Override
			public void handleMessage(Message msg) {
				MainActivity activity = mActivity.get();
				if(activity != null) {
					activity.handleMessage(msg);
				}
			}
		}
		
		private void handleMessage(Message msg) {
			progressDialog.dismiss();

			String result = msg.getData().getString(GoogleMapkiUtil.RESULT);
			ArrayList<String> searchList = new ArrayList<String>();

			if (result.equals(GoogleMapkiUtil.SUCCESS_RESULT)) {
				searchList = msg.getData().getStringArrayList("searchList");

			} else if (result.equals(GoogleMapkiUtil.TIMEOUT_RESULT)) {
				errorString = "error.";
				errorDialog.setMessage(errorString);
				errorDialog.show();
				return;
			} else if (result.equals(GoogleMapkiUtil.FAIL_MAP_RESULT)) {
				errorString = "error";
				errorDialog.setMessage(errorString);
				errorDialog.show();
				return;
			} else {
				errorString = httpUtil.stringData;
				errorDialog.setMessage(errorString);
				errorDialog.show();
				return;
			}
			
			String[] searches = searchList.toArray(new String[searchList.size()]);
			adjustToPoints(searches);
		}
		

		/**
		 * @param mPoints
		 */
		protected void adjustToPoints(String[] results) {
			
			mmap.clear();
			
			int length = Integer.valueOf(results.length / 3);
			LatLng[] mPoints = new LatLng[length];
			
			for (int i = 0; i < length; i++) {
				LatLng latlng = new LatLng(
	            		Float.valueOf(results[i * 3 + 1]),
	            		Float.valueOf(results[i * 3 + 2]));
				mmap.addMarker(new MarkerOptions()
	                    .position(latlng)
	                    .title(results[i * 3])
	                    .icon(BitmapDescriptorFactory.defaultMarker(i * 360 / length)));
	            
	            mPoints[i] = latlng;
	        }
			
			
			for (LatLng ll : mPoints) {

				// Sometimes the longitude or latitude gathering
				// did not work so skipping the point
				// doubt anybody would be at 0 0
				if (ll.latitude != 0 && ll.longitude != 0) {
					// Sets the minimum and maximum latitude so we can span and zoom
					minLatitude = (minLatitude > ll.latitude) ? ll.latitude : minLatitude;
					maxLatitude = (maxLatitude < ll.latitude) ? ll.latitude : maxLatitude;
					// Sets the minimum and maximum latitude so we can span and zoom
					minLongitude = (minLongitude > ll.longitude) ? ll.longitude	: minLongitude;
					maxLongitude = (maxLongitude < ll.longitude) ? ll.longitude	: maxLongitude;
				}
			}
			
			Log.d("dd", minLatitude + "/" +maxLatitude + "/"+minLongitude + "/"+maxLongitude);
			
			CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(new LatLngBounds(new LatLng(minLatitude, minLongitude), new LatLng(maxLatitude, maxLongitude)), 4);
			mmap.animateCamera(cu);
			
		}
	 
		private String getAddres(double lat, double lng) {
			Geocoder gcK = new Geocoder(getApplicationContext(), Locale.KOREA);
			String res = "雅뚯눘占쏙옙�몴占� 占쎌궡占쎈똻占쎈벉占쏙옙占쏙옙.";
			try {
				List<Address> addresses = gcK.getFromLocation(lat, lng, 1);
				StringBuilder sb = new StringBuilder();

				if (null != addresses && addresses.size() > 0) {
					Address address = addresses.get(0);
					sb.append(address.getLocality()).append("/");
					sb.append(address.getThoroughfare()).append("/");
					sb.append(address.getFeatureName());
					res = sb.toString();
				}

			} catch (IOException e) {
				e.printStackTrace();
			}
			return res;
		}
		
		protected String[] insert_location(Context context){
			String pString = null;
			HttpURLConnection conn = null;
			BufferedReader br = null;
			
			String[] result = new String[2];
			result[0] = "error"; //JSON flag
			result[1] = null; //message
			
			try{
	       	StringBuilder builder = new StringBuilder();
	       	
	       	URL url = new URL("http://54.199.194.197/insert_location.php");
	       	conn = (HttpURLConnection)url.openConnection();
	       	
	       	if(conn != null){
	       		conn.setConnectTimeout(15000);	
	       		conn.setReadTimeout(15000);
	       		conn.setDefaultUseCaches(false);
	           	conn.setDoInput(true); 
	           	conn.setDoOutput(true);  
	           	conn.setRequestMethod("POST"); 
	           	conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
	           	StringBuffer buffer = new StringBuffer();
	           	
	            buffer.append("latitude").append("=").append(lat).append("&");                 
	            buffer.append("longitude").append("=").append(lng);
	            
               OutputStreamWriter outStream = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
               PrintWriter writer = new PrintWriter(outStream);
               writer.write(buffer.toString());
               writer.flush();  

               InputStreamReader inputStream = new InputStreamReader(conn.getInputStream(), "UTF-8"); 
	           br = new BufferedReader(inputStream);
	              
	           	String line;
	           	while((line = br.readLine()) != null){
	           	   builder.append(line);
	           	}
	              
	           	br.close();
	           	
	           	pString =  builder.toString();
	           	locationID = pString;
	           	
	       	}else{
	       		
	       		throw new Exception("network error");
	       	}
	       	
	       }catch(SocketTimeoutException se){
	       	
	       	result[1] = "network error";
	       	
	       }catch(Exception e){
	       	
	       	result[1] = e.getMessage();
	       	
	       }finally{
	       	
	       	if(conn != null)
	       		conn.disconnect();

	       	if(br != null){
	       		try {
	       			br.close();
					} catch (Exception e2) {
						// TODO: handle exception
						result[1] = e2.getMessage();
					}
	       	}
	       }
	     
	       return result;
		}
		
		public class locaAsyncTask extends AsyncTask<String, String, String> {
			@Override
			protected void onPreExecute() {
				super.onPreExecute();
			}
			@Override
			protected String doInBackground(String... params) {
				insert_location(MainActivity.this);
				return null;
			}
			@Override
			protected void onPostExecute(String result) {
				mIntent = new Intent(MainActivity.this, WritePostActivity.class);
		        mIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		        mIntent.putExtra("userID", userID);
		        mIntent.putExtra("locationID", locationID);
	    		startActivity(mIntent);
				super.onPostExecute(result);
			}
			@Override
			protected void onCancelled() {
				super.onCancelled();
			}
		}

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			
		}
		
		Toast tempToast;
	    public void toMessage(String str){
	    	if(tempToast==null){
	    		tempToast = Toast.makeText(this, str, Toast.LENGTH_SHORT);
	    	}else{
	    		tempToast.setText(str);
	    	}
	    	tempToast.show();
	    }

	    public void toAlert(String str){
	    	new AlertDialog.Builder(this)
	    	.setMessage(str)
	    	.setCancelable(false)
	    	.setNegativeButton("�떕湲�", null)
	    	.show();
	    }
	    
	    public void toAlert(String title, String str){
	    	new AlertDialog.Builder(this)
	    	.setTitle(title)
	    	.setMessage(str)
	    	.setCancelable(false)
	    	.setNegativeButton("�떕湲�", null)
	    	.show();
	    }
	    
	    public void toLog(String str){ 
	    	Log.v("@#@===MY===@#@", str);
	    }
}
